from datetime import datetime

from rest_framework import serializers

from browse.models import Tag, Category, Post, Configration


class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = '__all__'


class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = '__all__'


class ConfigrationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Configration
        fields = '__all__'


class PostSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True)
    category = CategorySerializer()

    class Meta:
        model = Post
        fields = '__all__'

    def create(self, validated_data):
        tags_data = validated_data.pop('tags')
        category_data = validated_data.pop('category')
        if category_data['name'] != "未分类":
            category_object, res = Category.objects.get_or_create(name=category_data['name'])
            validated_data['category'] = category_object
        validated_data['pub_date'] = datetime.now()
        post = Post.objects.create(**validated_data)
        tags = []
        for tag in tags_data:
            t = Tag.objects.get_or_create(name=tag['name'])
            tags.append(t[0].id)
        post.tags.set(tags)
        post.save()
        return post

    def update(self, instance, validated_data):
        tags_data = validated_data.pop('tags', [])
        category_data = validated_data.pop('category', None)
        # Update category if data is provided
        if category_data:
            if category_data['name'] == "未分类":
                instance.category = None
            else:
                category_object, _ = Category.objects.get_or_create(name=category_data['name'])
                instance.category = category_object
        instance.__dict__.update(**validated_data)
        instance.save()
        # Update tags
        tags = [Tag.objects.get_or_create(name=tag_data['name'])[0] for tag_data in tags_data]
        instance.tags.set(tags)
        return instance


class PostListSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True)
    category = CategorySerializer()

    class Meta:
        model = Post
        exclude = ['content', ]
